package com.izhaowo.recommend.contrl;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.izhaowo.recommend.util.HBaseUtil;
import com.izhaowo.recommend.util.YeWuDBConn;
import com.izhaowo.recommend.vo.WeddingScenePhotoVO;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.util.Bytes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by HASEE on 2020/7/2.
 */
public class CalPlannerIndex {

    private static final Logger logger = LoggerFactory.getLogger(CalPlannerIndex.class);

    public static List<WeddingScenePhotoVO> getPhotoScore(String day) {
        day = day.replaceAll("[- :]", "").substring(0, 8);
        logger.info("___ getPhotoScore  is day : " + day);
        String reverse = new StringBuilder(day).reverse().toString();
        String endRow = reverse.substring(0, 7) + "3";
        return RecommendWeddingPlanner.getWeddingScenePhotoVO(reverse, endRow);
    }


    public static String calPhotoScore(Integer interval) {
        long start = System.currentTimeMillis();
        List<WeddingScenePhotoVO> list = getDayWeddingPhoto(interval);
        List plannerList = RecommendWeddingPlanner.getPhotoPlanners(null);
        int photoSize = list.size();
        int plannerSize = plannerList.size();
        logger.info("___ photo size is  " + photoSize + " , planner size is " + plannerSize);

        if (photoSize == 0 || plannerSize == 0) {
            return "fail";
        }

        Random random = new Random();
        int count = 0;
        Set<Integer> indexSet = new HashSet<>();
        List<WeddingScenePhotoVO> result = new ArrayList<>(20);
        int size = photoSize > plannerSize ? plannerSize : photoSize;
        if (photoSize > plannerSize) {
            for (int i = 0; i < size; i++) {
                while (indexSet.size() < size) {
                    int temp = random.nextInt(photoSize);
                    count++;
                    if (indexSet.contains(temp)) {
                        temp = (temp + 1) % size;
                    }
                    if (!indexSet.contains(temp)) {
                        WeddingScenePhotoVO vo = new WeddingScenePhotoVO();
                        BeanUtils.copyProperties(list.get(temp), vo);
                        BeanUtils.copyProperties(plannerList.get(i), vo);
                        result.add(vo);
                        indexSet.add(temp);
                        break;
                    }
                }
            }
        } else {
            for (int i = 0; i < size; i++) {
                while (indexSet.size() < size) {
                    count++;
                    int temp = random.nextInt(plannerSize);
                    if (indexSet.contains(temp)) {
                        temp = (temp + 1) % size;
                    }
                    if (!indexSet.contains(temp)) {
                        WeddingScenePhotoVO vo = new WeddingScenePhotoVO();
                        BeanUtils.copyProperties(list.get(i), vo);
                        BeanUtils.copyProperties(plannerList.get(temp), vo);
                        indexSet.add(temp);
                        result.add(vo);
                        break;
                    }
                }
            }
        }

        if (result.size() > 0) {
            putResult(result, interval);
        }
        long end = System.currentTimeMillis();

        logger.info("____ speeds time is " + (end - start) + " count is  " + count);
        return "success";
    }

    public static void putResult(List<WeddingScenePhotoVO> result, Integer interval) {
        List<Put> puts = new ArrayList<>();
        int size = result.size();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        cal.add(Calendar.DATE, 1 - interval);
        String day = sdf.format(cal.getTime());
        String rowKey = new StringBuilder(day).reverse().toString();
        Gson gson = new Gson();
        for (int i = 0; i < size; i++) {
            Put put = new Put(Bytes.toBytes(rowKey + "_" + i));
            String data = gson.toJson(result.get(i));
            JsonObject json = new JsonParser().parse(data).getAsJsonObject();
            Iterator it = json.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String, JsonElement> map = (Map.Entry<String, JsonElement>) it.next();
                String col = map.getKey().replaceAll("\"", "");
                String val = json.get(map.getKey()).toString().replaceAll("\"", "");
                put.addColumn(Bytes.toBytes("info"), Bytes.toBytes(col), Bytes.toBytes(val));
            }
            puts.add(put);
        }
        try {
            HBaseUtil.put("planner_photo_prescore_result", puts);
            logger.info("____ planner photo  puts  size is  " + puts.size());
        } catch (Exception e) {
            logger.info("____ planner photo error is : ", e.getMessage());
        }
    }

    public static List<WeddingScenePhotoVO> getDayWeddingPhoto(Integer interval) {
        StringBuilder sb = new StringBuilder();
        sb.append(" select  id,user_wedding_id,upload_worker_id,ctime from izhaowo_user_wedding.tb_wedding_scene_photo ").
                append(" where  ctime >= DATE_SUB(now(),INTERVAL ").append(interval).
                append(" DAY) and ctime <= DATE_SUB(now(),INTERVAL  ").append(interval - 1).append(" DAY )");

        logger.info("___  sql is  " + sb.toString());
        List<WeddingScenePhotoVO> list = new ArrayList<>(20);
        try {
            Connection con = YeWuDBConn.getConnection();
            Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery(sb.toString());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            while (rs.next()) {
                WeddingScenePhotoVO vo = new WeddingScenePhotoVO();
                vo.setId(rs.getString(1));
                vo.setUser_wedding_id(rs.getString(2));
                vo.setUpload_worker_id(rs.getString(3));
                vo.setCtime(sdf.format(rs.getDate(4)));
                list.add(vo);
            }
            con.close();
        } catch (Exception e) {
            logger.error("___" + e.getMessage());
        }
        return list;
    }


    public static void main(String[] args) {
//        calPhotoScore(1);
//        Random random = new Random();
//        for (int i = 0; i < 10; i++) {
//            System.out.println(random.nextInt(2));
//        }
//        StringBuilder sb = new StringBuilder();
//        sb.append(" select  id,user_wedding_id,upload_worker_id,ctime from izhaowo_user_wedding.tb_wedding_scene_photo ").
//                append(" where  ctime >= DATE_SUB(now(),INTERVAL ").append(1).
//                append(" DAY) and ctime <= DATE_SUB(now(),INTERVAL  ").append(1 - 1).append(" DAY )");
//
//        logger.info("___  sql is  " + sb.toString());
//
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
//        Calendar cal = Calendar.getInstance();
//        cal.setTime(new Date());
//        cal.add(Calendar.DATE, -1);
//        logger.info(sdf.format(cal.getTime()));
        String a = "20200701".replaceAll("[- :]", "");

        logger.info("___--" + a);//.substring(0, 8);
    }

}
